package middleware

import (
	"github.com/gin-gonic/gin"
	"go_api/model"
	"net/http"
)

func ApiMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			token = c.Query("token")
		}
		if token == "" {
			c.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code":    401,
				"message": "缺少认证信息",
				"data":    nil,
			})
			return
		}
		//根据token获取用户信息
		userModel := model.XUser{}
		userInfo, err := userModel.GetUserByToken(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code":    401,
				"message": "认证信息已过期",
				"data":    nil,
			})
		}

		if userInfo == nil {
			c.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code":    401,
				"message": "认证信息已过期",
				"data":    nil,
			})
		}

		c.Set("uId", userInfo.ID)
		c.Next()
	}
}
